<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>tab栏切换</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            margin: 50px auto;
            width: 300px;
            border: 1px solid #000000;
        }

        .box>.top {
            /* 行内元素去除空隙 */
            font-size: 0;
        }

        .box>.top>button {
            width: 60px;
            height: 50px;
            font-size: 18px;
            border: none;
            outline: none;
        }

        /* button 选中时的样式 */
        .box>.top>button.selected {
            background-color: green;
            color: red;
        }

        .box>.bottom>div {
            display: none;
            height: 300px;
            background-color: yellow;

        }

        .box>.bottom>div:nth-child(1) {
            display: block;
        }
    </style>
    <script>
        window.onload = function () {
            // 1. 获取所有的按钮
            // var btns = document.querySelectorAll('button');
            var btns = document.getElementsByClassName('top')[0].children
            var divs = document.getElementsByClassName('bottom')[0].children
            // 2. 对button进行循环遍历，注册点击事件
            for (var i = 0; i < btns.length; i++) {
                // 动态的给每一个button按钮添加一个属性，index，并赋值为i
                btns[i].index = i
                btns[i].onclick = function () {
                    // 3. 点击时，给当前按钮添加类名,并且去除兄弟元素的该类名
                    // 排他思想
                    for (var j = 0; j < btns.length; j++) {
                        btns[j].className = ''
                        divs[j].style.display = "none"
                    }
                    this.className = 'selected'
                    divs[this.index].style.display = "block"
                }
            }
        }


    </script>
</head>

<body>
    <div class="box">
        <div class="top">
            <button class="selected">按钮1</button>
            <button>按钮2</button>
            <button>按钮3</button>
            <button>按钮4</button>
            <button>按钮5</button>
        </div>
        <div class="bottom">
            <div>盒子1</div>
            <div>盒子2</div>
            <div>盒子3</div>
            <div>盒子4</div>
            <div>盒子5</div>
        </div>
    </div>
</body>

</html>